import os
import uuid
import zipfile
from django.contrib import admin
from django.core.files.base import ContentFile
from .models import Album, AlbumImage
from .forms import AlbumForm


# Register your models here.
@admin.register(Album)
class AlbumModelAdmin(admin.ModelAdmin):
    form = AlbumForm
    prepopulated_fields = {'slug': ('title',)}
    list_display = ('title', 'thumb')
    list_filter = ('create_date',)

    def save_model(self, request, obj, form, change):
        """
        Django自带的save_model方法为admin界面用户保存model实例时的行为。
        :param request:HttpRequest实例
        :param obj:model实例
        :param form:ModelForm实例
        :param change:bool值，取决于model实例是新增的还是修改的。
        :return:
        """
        if form.is_valid():
            album = form.save()

            if form.cleaned_data['zip'] is not None:
                zip = zipfile.ZipFile(form.cleaned_data['zip'])
                for filename in sorted(zip.namelist()):

                    file_name = os.path.basename(filename)
                    if not file_name:
                        continue

                    data = zip.read(filename)
                    contentfile = ContentFile(data)

                    img = AlbumImage()
                    img.album = album
                    filename = '{0}{1}.jpg'.format(album.slug[:8], str(uuid.uuid4())[-13:])
                    img.alt = filename
                    img.image.save(filename, contentfile)

                    img.thumb.save('thumb-{0}'.format(filename), contentfile)
                    img.save()
                zip.close()
            super().save_model(request, obj, form, change)


# In case image should be removed from album.
@admin.register(AlbumImage)
class AlbumImageModelAdmin(admin.ModelAdmin):
    list_display = ('alt', 'album')
    list_filter = ('album', 'create_date')
    exclude = ['thumb']

    def save_model(self, request, obj, form, change):
        if form.is_valid():
            img = form.save(commit=False)
            slug = form.cleaned_data['album'].slug

            filename = '{0}{1}'.format(slug[:8], str(uuid.uuid4())[-13:])
            img.alt = filename
            img.image.save(filename, form.cleaned_data['image'])

            img.thumb.save('thumb-{0}'.format(filename), form.cleaned_date['image'])
            img.save()

            super().save_model(request, obj, form, change)